package myUtils.page;

import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import myUtils.Constants;
import org.hibernate.Session;

public class Result {
	
	private Page page; 
	private List<?> content;
  
	/**
	 * The default constructor
	 */
	public Result() {
		super();
	}

	/**
	 * The constructor using fields
	 * 
	 * @param page
	 * @param content
	 */
	public Result(Page page, List<?> content)
    {
		this.page = page;
		this.content = content;
	}

    public Result(int page,List<?> content)
    {
         Page p=PageUtil.createPage(page, content.size());
         int to=page*p.getEveryPage()>=content.size()?content.size():page*p.getEveryPage();
         this.page=p;
         this.content=content.subList((p.getCurrentPage()-1)*p.getEveryPage(), to);
    }

    public Result(int page, HibernateDaoSupport dao, String queryString)
    {
        int count=getCount(dao,queryString);
        Session session=dao.getSessionFactory().openSession();
        this.content=session.createQuery(queryString).setFirstResult((page-1)*Constants.ITEM_PER_PAGE).setMaxResults(Constants.ITEM_PER_PAGE).list();
        this.page=PageUtil.createPage(page, count);
    }

    public int getCount(HibernateDaoSupport dao, String queryString)
    {
        Session session=dao.getSessionFactory().openSession();
        int count=((Long)session.createQuery("select count(*) "+queryString).uniqueResult()).intValue();
        System.out.println("count : "+count);
        return count;
    }

	/**
	 * @return Returns the content.
	 */
	public List<?> getContent() {
		return content;
	}

	/**
	 * @return Returns the page.
	 */
	public Page getPage() {
		return page;
	}

	/**
	 * @param content
	 *            The content to set.
	 */
	public void setContent(List<?> content) {
		this.content = content;
	}

	/**
	 * @param page
	 *            The page to set.
	 */
	public void setPage(Page page) {
		this.page = page;
	}
}
